<?php

namespace App\Console\Commands\Amap;

use App\Models\Common\ConfigModel;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;

class CheckConfigWebApiKeyStatus extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'amap:checkConfigWebApiKeyStatus';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '检查高德web服务api的key状态';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     */
    public function handle()
    {
        /*
         * 设计思路
         * 1. 通过遍历所有的key，查询北京的天气情况
         * 2. 如果有数据，则key正常 反之异常
         */

        $config = ConfigModel::getValueNewJson('amap', 'webServeApiKey');

        if ('' == $config) {
            return null;
        }

        $errorKey = $config['error'];  // 错误的key收集

        $normalKey = collect($config['normal'])->map(function ($amapKey) use (&$errorKey) {
            usleep(500000);
            $res = Http::withOptions([
                'http_errors' => false,
            ])->withHeaders([
                'accept' => 'application/json',
            ])->get('https://restapi.amap.com/v3/weather/weatherInfo?city=110101&key=' . $amapKey['key'])->json();

            if (isset($res['status']) && $res['status'] == 1) {
                $this->info('正常的key:' . $amapKey['key']);
                $amapKey['updateTime'] = time();
                return $amapKey;
            }
            $this->info('错误的key:' . $amapKey['key']);
            $errorKey[] = array_merge($amapKey, ['time' => Carbon::now()->toDateTimeString()]);

            return null;

        })->filter()->values()->toArray();

        $new = [
            'normal' => $normalKey,
            'error'  => $errorKey
        ];

        ConfigModel::setValue('amap', 'webServeApiKey', json_encode($new, JSON_UNESCAPED_UNICODE));
    }
}
